﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Configuration;

namespace MS.Common.Helpers
{
    public sealed class ConfigHelper
    {
        #region appSettings节点
        /// <summary>
        /// 获取配置文件指定的值
        /// </summary>
        /// <param name="key">健</param>
        /// <param name="defaultvalue">值为Null时返回的默认值</param>
        /// <returns>健对应的值，如果为Null返回默认值</returns>
        public static string GetConfig(string key, string defaultvalue)
        {
            string _value = GetConfig(key);
            return string.IsNullOrEmpty(_value) ? defaultvalue : _value;
        }
        /// <summary>
        /// 获取配置文件指定的值
        /// </summary>
        /// <param name="key">健</param>
        /// <returns>健对应的值</returns>
        public static string GetConfig(string key)
        {
            if (string.IsNullOrEmpty(key)) return string.Empty;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                if (config.AppSettings.Settings[key] == null)
                    return string.Empty;
                else
                    return config.AppSettings.Settings[key].Value;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// appSettings节点下是否存在某健
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExistKey(string key)
        {
            if (string.IsNullOrEmpty(key)) return false;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            return config.AppSettings.Settings[key] != null;
        }

        /// <summary>
        ///　对appSettings节点添加健值
        ///　如果健已经存在则更改值
        ///　添加后重新保存并刷新该节点
        /// </summary>
        /// <param name="key">添加的健</param>
        /// <param name="key">添加的值</param>
        public static void AddConfig(string key, string value)
        {
            if (string.IsNullOrEmpty(key)) return;
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                if (IsExistKey(key))
                    configuration.AppSettings.Settings[key].Value = value;
                else
                    configuration.AppSettings.Settings.Add(key, value);

                configuration.Save();
            }
            catch (Exception)
            {
                throw;
            }
            ConfigurationManager.RefreshSection("appSettings");
        }
        /// <summary>
        ///　对appSettings节点添加健值,一次添加或更改多个健值
        ///　如果健已经存在则更改值
        ///　添加后重新保存并刷新该节点
        ///　默认不加密该appSettings节点数据
        /// </summary>
        /// <param name="dict">添加的健值集合</param>
        public static void AddConfig(System.Collections.Generic.Dictionary<string, string> dict)
        {
            AddConfig(dict, false);
        }
        /// <summary>
        ///　对appSettings节点添加健值
        ///　如果健已经存在则更改值
        ///　添加后重新保存并刷新该节点
        ///　加密后的配置节不能通过ConfigurationManager.AppSettings[key]进行访问,否则会产生错误"无法识别的属性 configProtectionProvider"
        ///　可以通过Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings[key]进行访问
        /// </summary>
        /// <param name="dict">添加的健值集合</param>
        /// <param name="isProtected">是否加密appSettings节点数据,如果为TrueappSettings节点下所有数据都会被加密</param>
        public static void AddConfig(System.Collections.Generic.Dictionary<string, string> dict, bool isProtected)
        {
            if (dict == null || dict.Count <= 0) return;
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            #region  //循环添加或更改健值
            foreach (System.Collections.Generic.KeyValuePair<string, string> key_value in dict)
            {
                if (string.IsNullOrEmpty(key_value.Key)) continue;
                if (IsExistKey(key_value.Key))
                    configuration.AppSettings.Settings[key_value.Key].Value = key_value.Value;
                else
                    configuration.AppSettings.Settings.Add(key_value.Key, key_value.Value);
            }//end foreach
            #endregion
            #region 保存配置文件
            try
            {
                //加密配置信息
                if (isProtected && !configuration.AppSettings.SectionInformation.IsProtected)
                {
                    configuration.AppSettings.SectionInformation.ForceSave = true;

                    configuration.AppSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                }
                configuration.Save();

            }
            catch (Exception)
            {
                throw;
            }
            ConfigurationManager.RefreshSection("appSettings");
            ConfigurationManager.RefreshSection("configuration");
            #endregion
        }
        /// <summary>
        /// 删除AppSettings下指定的Name
        /// </summary>
        /// <param name="key">要删除的Name</param>
        /// <returns></returns>
        public static bool Remove(string key)
        {
            if (!IsExistKey(key)) return false;
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings.Remove(key.Trim());
            try
            {
                configuration.Save();
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
        #region connectionStrings节点
        /// <summary>
        /// ConnectionStrings.Count
        /// </summary>
        /// <returns></returns>
        public static int GetConnsCount
        {
            get { return ConfigurationManager.ConnectionStrings.Count; }
        }
        /// <summary>
        ///  读取数据库配置文件(connectionStrings节点)
        /// </summary>
        /// <param name="key">健名</param>
        /// <returns></returns>
        public static string GetConnConfig(string key)
        {
            return !string.IsNullOrEmpty(key) && ConfigurationManager.ConnectionStrings[key] != null ? ConfigurationManager.ConnectionStrings[key].ConnectionString : string.Empty;
        }
        /// <summary>
        /// 健不存在或值为Null
        /// </summary>
        /// <param name="key">健名</param>
        /// <returns></returns>
        public static bool GetConfigConnIsNull(string key)
        {
            return string.IsNullOrEmpty(key) || ConfigurationManager.ConnectionStrings[key] == null || string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[key].ConnectionString);
        }
        /// <summary>
        /// 保存配置数据库连接字符串 
        /// 如果不存在连接字符串，则创建并设置字符串
        /// </summary>
        /// <param name="key">要操作的节点</param>
        /// <param name="value">值</param>
        public static void AddConnConfig(string key, string value)
        {
            if (string.IsNullOrEmpty(key)) return;
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (configuration.ConnectionStrings.ConnectionStrings[key] == null)
                configuration.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, value));
            else
            {
                foreach (ConnectionStringSettings conn in configuration.ConnectionStrings.ConnectionStrings)
                {
                    if (conn.Name != key || conn.ConnectionString == value) continue;
                    conn.ConnectionString = value;
                    break;
                }
            }
            try
            {
                configuration.Save();
            }
            catch (Exception)
            {
                throw;
            }
            ConfigurationManager.RefreshSection("connectionStrings");
        }
        #endregion
    }
}
